#!/usr/bin/env bash
#
# Copyright (C) Hygon Info Technologies Ltd.
#
# SPDX-License-Identifier: Apache-2.0
#

. /opt/hygon/common.sh
set -x
set -o errexit
set -o errtrace
set -o pipefail

readonly script_name="$(basename "${BASH_SOURCE[0]}")"
readonly script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

readonly cc_tar_name="confidential-containers.tar.xz"
readonly kbs_tar_name="simple-kbs.tar.gz"
readonly pkg_dir="${script_dir}/../pkg"
mkdir -p ${pkg_dir}

lib_file="${script_dir}/lib.sh"
source "$lib_file"
os_release=$(eval get_os_release)

install_dependencies() {
    info "install dependencies ..."
    case $os_release in
    "ubuntu")
        # used by signing container images.
        info "install cosign ..."
        pushd "${pkg_dir}"
        # download from https://github.com/sigstore/cosign/releases
        if [ ! -f cosign_2.0.2_amd64.deb ]; then
            /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/cosign_2.0.2_amd64.deb ./cosign_2.0.2_amd64.deb
        fi
        dpkg -i cosign_2.0.2_amd64.deb
        popd
    ;;
    "anolis")
        setenforce  0 ||true
        systemctl disable firewalld.service
        systemctl stop firewalld.service
        if [ ! -f ${pkg_dir}/cosign-linux-amd64 ]; then
            /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/cosign-linux-amd64 ${pkg_dir}/cosign-linux-amd64
        fi
        install -D ${pkg_dir}/cosign-linux-amd64 /usr/bin/cosign
    ;;
    "kylin")
        setenforce  0 ||true
        systemctl disable firewalld.service
        systemctl stop firewalld.service
        if [ ! -f ${pkg_dir}/cosign-linux-amd64 ]; then
            /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/cosign-linux-amd64 ${pkg_dir}/cosign-linux-amd64
        fi
        if [ ! -f ${pkg_dir}/runc.amd64 ]; then
            /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/runc.amd64 ${pkg_dir}/runc.amd64
        fi
        if [ ! -f ${pkg_dir}/jq-linux64 ]; then
            /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/jq-linux64 ${pkg_dir}/jq-linux64
        fi
        install -D ${pkg_dir}/cosign-linux-amd64 /usr/bin/cosign
        install -D ${pkg_dir}/runc.amd64 /usr/local/bin/runc.amd64
        install -D ${pkg_dir}/jq-linux64 /usr/bin/jq
    ;;

    esac
    # used by encrypting container images.
    info "install skopeo ..."
    pushd "${pkg_dir}"
    if [ ! -f skopeo ]; then
        /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/skopeo ./skopeo
    fi
    install -D skopeo /usr/bin/skopeo
    popd
    skopeo -v

}


start_docker_service() {
    info "starting docker service ..."
    mkdir -p /etc/docker
    [ -f /etc/docker/daemon.json ] && mv -f /etc/docker/daemon.json /etc/docker/daemon.json_bk
    cp -f ${script_dir}/../config/daemon.json  /etc/docker/daemon.json
    case $os_release in
    "ubuntu" | "anolis" )
        systemctl enable --now docker
        systemctl daemon-reload
        service docker restart
    ;;
    "kylin")
        service containerd stop
        systemctl enable --now docker
        systemctl daemon-reload
        service docker restart
        service containerd restart
    ;;
    esac
}

install_confidential_containers() {
    info "install confidential containers ..."
    pushd ${pkg_dir}
    if [ ! -f ${cc_tar_name} ]; then
        /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/${cc_tar_name} ./${cc_tar_name}
    fi
    tar -xvJf ${cc_tar_name} -C /
    popd
}

set_containerd_mirror_accelerator()
{
# Path to the config.toml file
config_file="/etc/containerd/config.toml"

# Insert point: [plugins."io.containerd.grpc.v1.cri".registry.mirrors]
insert_marker='\[plugins."io.containerd.grpc.v1.cri".registry.mirrors\]'

# Check if the marker exists in the config file
if grep -q "$insert_marker" "$config_file"; then
  echo "$insert_marker exists, checking if docker.io and k8s.gcr.io mirror configurations need to be inserted..."

  # Check and insert docker.io mirror configuration
  if ! grep -q '\[plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"\]' "$config_file"; then
    echo "Inserting docker.io mirror configuration..."
    # Insert the docker.io mirrors under the insert_marker using heredoc to handle multiple lines
    sed -i "/$insert_marker/a\\
        [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"docker.io\"]\n\
          endpoint = [\"https:\/\/docker.m.daocloud.io\",\"https:\/\/noohub.ru\",\"https:\/\/huecker.io\",\"https:\/\/dockerhub.timeweb.cloud\",\"https:\/\/registry.cn-hangzhou.aliyuncs.com\",\"https:\/\/mirror.ccs.tencentyun.com\",\"https:\/\/docker.mirrors.ustc.edu.cn\",\"https:\/\/hub-mirror.c.163.com\"]" "$config_file"
  else
    echo "docker.io mirror configuration already exists, skipping insertion."
  fi

  # Check and insert k8s.gcr.io mirror configuration
  if ! grep -q '\[plugins."io.containerd.grpc.v1.cri".registry.mirrors."k8s.gcr.io"\]' "$config_file"; then
    echo "Inserting k8s.gcr.io mirror configuration..."
    # Insert the k8s.gcr.io mirrors under the insert_marker using heredoc to handle multiple lines
    sed -i "/$insert_marker/a\\
        [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"k8s.gcr.io\"]\n\
          endpoint = [\"https:\/\/registry.aliyuncs.com\/google_containers\"]" "$config_file"
  else
    echo "k8s.gcr.io mirror configuration already exists, skipping insertion."
  fi

else
  echo "$insert_marker not found, cannot insert. Please ensure the config.toml file contains this marker."
fi

echo "Operation completed."
}


configure_containerd() {
    info "configure containerd ..."
    [ ! -d /etc/containerd/ ] && mkdir -p /etc/containerd/ || true
    case $os_release in
    "ubuntu" | "anolis")
        containerd config default > /etc/containerd/config.toml
        sed -i 's#registry.k8s.io/pause#registry.cn-hangzhou.aliyuncs.com/google_containers/pause#g' /etc/containerd/config.toml
    ;;
    "kylin")
        /opt/confidential-containers/bin/containerd config default > /etc/containerd/config.toml
        sudo sed -i 's/BinaryName = ""/BinaryName = "runc.amd64"/' /etc/containerd/config.toml
        cp -f /opt/hygon/csv/confidential-containers/config/containerd.service /etc/systemd/system/containerd.service
        sed -i 's#k8s.gcr.io/pause#registry.cn-hangzhou.aliyuncs.com/google_containers/pause#g' /etc/containerd/config.toml
    ;;
    esac
    set_containerd_mirror_accelerator
    mkdir -p /etc/systemd/system/containerd.service.d
cat >/etc/systemd/system/containerd.service.d/containerd-for-cc-override.conf<<EOF
[Service]
ExecStart=
ExecStart=/opt/confidential-containers/bin/containerd
EOF
}

start_containerd_service() {
    info "starting containerd service ..."
    sudo systemctl enable --now containerd
    sudo systemctl daemon-reload
    sudo service containerd restart
}

install_simple_kbs() {
    info "install simple-kbs ..."
    pushd ${pkg_dir}
    if [ ! -f ${kbs_tar_name} ]; then
        /opt/hygon/tools/sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/simple-kbs.tar.gz ./${kbs_tar_name}
    fi
    tar xvf ${kbs_tar_name} -C /opt/
    popd
}

enable_kata_runtime_for_containerd() {
    cat >>/etc/containerd/config.toml<<EOF
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata]
  cri_handler = ""
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration.toml"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu]
  cri_handler = "cc"
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration-qemu.toml"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv]
  cri_handler = "cc"
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration-qemu-csv.toml"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv-dcu]
  cri_handler = "cc"
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv-dcu.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration-qemu-csv-dcu.toml"
EOF
}

setup_module_load() {
    echo "br_netfilter" > /etc/modules-load.d/br_netfilter.conf
    echo "vfio-pci" > /etc/modules-load.d/vfio.conf

    tee /etc/modules-load.d/vhost.conf <<EOF
vhost-vsock
vhost-net
EOF

modprobe br_netfilter
modprobe vfio-pci
modprobe vhost-vsock
modprobe vhost-net
}

setup_permissions() {
    sed -ri '/\sswap\s/s/^#?/#/' /etc/fstab
    swapoff -a

    tee /etc/sysctl.d/kubernetes.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
    sysctl --system
}

main() {
    check_root

    install_dependencies

    setup_module_load
    setup_permissions

    install_confidential_containers
    configure_containerd
    enable_kata_runtime_for_containerd
    start_containerd_service
    start_docker_service

    install_simple_kbs

    OK "Environment is set up, Enjoy!"
}

main $*
